package com.quanyan.pay.service.impl;

import com.quanyan.alipay.config.AlipayConfig;
import com.quanyan.common.encrypt.AESCoder;
import com.quanyan.pay.entity.AccountPayRelation;
import com.quanyan.pay.entity.AlipayAccount;
import com.quanyan.pay.mapper.AlipayAccountMapper;
import com.quanyan.pay.service.AccountPayRelationService;
import com.quanyan.pay.service.PayConfigService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * Created by Zheng.Ke
 * Date 2016/8/8.
 */
@Service("payConfigService")
public class PayConfigServiceImpl implements PayConfigService {
    private static Logger logger = LoggerFactory.getLogger(PayConfigServiceImpl.class);

    @Value("${ali.pay.callback}")
    private String ALI_PAY_CALLBACK;
    @Value("${ali.pay.refund.callback}")
    private String ALI_PAY_REFUND_CALL_BACK;
    @Value("${ali.pay.withdraw.callback}")
    private String ALI_PAY_WITHDRAW_CALL_BACK;
    @Autowired
    private AccountPayRelationService accountPayRelationService;
    @Autowired
    private AlipayAccountMapper alipayAccountMapper;

    @Override
    public AlipayConfig getAlipayConfig(String mchId, Integer payId) {
        AccountPayRelation accountPayRelation = accountPayRelationService.getAccountPayRelation(mchId, payId);
        if (accountPayRelation == null) {
            logger.error("支付宝支付数据库没有配置好。mchId={},payId={}", mchId, payId);
        }
        AlipayAccount alipayAccount = alipayAccountMapper.selectByPrimaryKey(accountPayRelation.gettAId());
        alipayAccount.setPrivateKey(AESCoder.decodeContent(alipayAccount.getPrivateKey()));
        alipayAccount.setPublicKey(AESCoder.decodeContent(alipayAccount.getPublicKey()));
        alipayAccount.setAliKey(AESCoder.decodeContent(alipayAccount.getAliKey()));

        return new AlipayConfig.Builder()
                .setAli_public_key(alipayAccount.getPublicKey())
                .setKey(alipayAccount.getAliKey())
                .setPartner(alipayAccount.getPartner())
                .setPrivate_key(alipayAccount.getPrivateKey())
                .setSeller(alipayAccount.getSeller())
                .setNotify_url(ALI_PAY_CALLBACK)
                .setRefund_notify_url(ALI_PAY_REFUND_CALL_BACK)
                .setWithdraw_notify_url(ALI_PAY_WITHDRAW_CALL_BACK)
                .setApp_id(alipayAccount.getAppId())
                .build();
    }
}
